// my/wx.js
import {
  RechargeModel
} from '../../models/recharge'
import {
  PayModel
} from '../../models/pay'
import {
  Format
} from '../../utils/common'
import {
  AccountModel
} from '../../models/account'
import {
  InvioceModel
} from '../../models/invioce'
const invioceModel = new InvioceModel()
const accountmodel = new AccountModel()
const payModel = new PayModel()
const rechargeModel = new RechargeModel()
const app = getApp()
let last
const format = new Format()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    recharge: {},
    tabs: [
      {
        title: '立即充值',
      },
      {
        title: '历史账单',
      }
    ],
    activeTab: 0,
    btnDisabled: true,
    inputDisabled: true, //选择油枪
    checkBox: true,
    modalOpened4: false,
    openTicketType: '',
    rechargeActive: '', //充值活动
    payAmountInput: '',
    radioitems: [
      {name: '花呗分期', value: 7, checked: false, icon: '/assets/payIcon4.jpg',arrowType: 'circle'},
    ],
    huabeiSelect: false, //花呗分期默认选中
    huabei: [], // 花呗list
    taxRate: [0.023,0.045,0.075],
    payType: 2,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      'options': JSON.stringify(options),
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showLoading({
      content: '加载中',
    })
    app.myLogin().then(res => {
      console.log('myLogin' + JSON.stringify(res))
      // this.loadUserInfo()
      const pat = /(\d{3})\d*(\d{4})/;
      console.log('data' + JSON.stringify(app.globalData.user) )
      if (res.phone) {
        this.setData({
          inputDisabled: false,
          'recharge[phone]': res.phone,
          'recharge[mobileValue]': res.phone.replace(pat, '$1****$2'),
          'recharge[cardAsn]': res.cardAsn,
          openTicketType: res.openTicketType
        });
        // this.checkOriginPwd()
        this.getActiveParam()
        // if (app.globalData.ifSetPaw && app.globalData.ifSetPaw == 1) {
        //   this.getActiveParam()
        // } else {
        //   this.checkOriginPwd()
        // }
        // if (app.globalData.ifSetPaw == 0 ) {
        //   this.setData({
        //     modalOpened4: true,
        //   });
        // } else if (app.globalData.ifSetPaw == 1) {
        // } else {
        //   this.checkOriginPwd()
        // }
      }
      setTimeout(() => {
        wx.hideLoading();
      }, 1000);

    })
  },
  handleTabClick({ index }) {
    this.setData({
      activeTab: index,
    });
  },
  handleTabChange({ index }) {
    this.setData({
      activeTab: index,
    });
  },
  changePayAmount(e) {
    if (this.data.inputDisabled) {
      this.tip()
      return
    }
    const currentQuickIndex = e.currentTarget.dataset.index
    const currentPayInput = this.data.quickAmount[currentQuickIndex]
    let taxRate = this.data.taxRate
    if (this.data.payType == 7) {
      let payAmountInput = currentPayInput.price
      this.setData({
        huabeiIndex: 0,
        'huabei': [{serviceCharge: parseInt(payAmountInput*100*taxRate[0]/3),taxRate: taxRate[0],number: 3,periodCost: parseInt(payAmountInput*100/3) + parseInt(payAmountInput*100*taxRate[0]/3)},
                  {serviceCharge: parseInt(payAmountInput*100*taxRate[1]/6),taxRate: taxRate[1],number: 6,periodCost: parseInt(payAmountInput*100/6)+parseInt(payAmountInput*100*taxRate[1]/6)},
                  {serviceCharge: parseInt(payAmountInput*100*taxRate[2]/12),taxRate: taxRate[2],number: 12,periodCost: parseInt(payAmountInput*100/12) +parseInt(payAmountInput*100*taxRate[2]/12)}],
        'selectHuabei' : {serviceCharge: parseInt(payAmountInput*100*taxRate[0]/3),taxRate: taxRate[0],number: 3,periodCost: parseInt(payAmountInput*100/3) + parseInt(payAmountInput*100*taxRate[0]/3)}
      })
    }
    this.setData({
      currentQuickIndex:currentQuickIndex,
      payAmountInput: currentPayInput.price + '',
      realAmount: format.amount(currentPayInput.price * 100),
      btnDisabled: false
    })
    console.log(currentQuickIndex)
  },
  onInput(e) {
    last = e.timeStamp
    this.setData({
      currentQuickIndex: 12
    })
    var mesValue
    if (!(e.detail.value)) {
      this.setData({
        btnDisabled: true,
        payAmountInput: ''

      })
      return
    }
    console.log(e.detail.value)
    if (/^\d{1,5}(\.\d{0,2})?$/.test(e.detail.value)) {
      //满足条件
      mesValue = e.detail.value;
    } else {
      //不满足条件
      mesValue = e.detail.value.substring(0, e.detail.value.length - 1);
      wx.showToast({
        type: 'none',
        content: '支付金额仅支持小数点前5位，小数点后2位',
        duration: 600,
      });
    }
    if (!mesValue) {
      this.setData({
        btnDisabled: true
      })
    } else {
      this.setData({
        btnDisabled: false
      })
    }
    this.setData({
      payAmountInput: mesValue
    })
  },
  onFocus(e) {
    this.setData({
        'huabeiIndex': 0,
        'payType': 2,
        huabeiSelect: false,
    })
  },
  onChange(e) {
    console.log(e);
    this.setData({
      checkBox: e.detail.value,

    });
  },
  tip(e) {
    let vm = this
    const pat = /(\d{3})\d*(\d{4})/;
    if (this.data.inputDisabled) {
      wx.getPhoneNumber({
        success: (res) => {
            let encryptedData = res.response;
            app.myoilLogin(encryptedData).then(res => {
              console.log('myoilLogin------' + JSON.stringify(res))
              if (res.result == 500) {
                wx.showToast({
                  type: 'none',
                  content: res.message,
                  duration: 1000,
                });
                return
              }
              vm.setData({
                'recharge[phone]': res.data.phoneNum,
                'recharge[mobileValue]': res.data.phoneNum.replace(pat, '$1****$2'),
                'recharge[cardAsn]': res.data.cardAsn

              });
              vm.setData({
                inputDisabled: false,

              });
              vm.getCouponListByOrderId()
            })
        },
        fail: (res) => {
            console.log(res);
            console.log('getPhoneNumber_fail');
            wx.showToast({
              type: 'none',
              content: 'getPhoneNumber~失败',
              duration: 1000,
            });
        },
      });
      
    } else {
      vm.setData({
        inputDisabled: false,

      });
      const page = e.currentTarget.dataset.url
      if (page =='/pages/myOrder/myOrder'){
        wx.navigateTo({
          url: page + '?activeTab=1'
        })
      }
    }
  },
  toPay() {
    // wx.reLaunch({
    //   url: '/pages/rechargeResult/rechargeResult'
    // })
    const d = this.data
    const amount = (d.payAmountInput * 100).toFixed(0)
    if (amount <= 0) {
      wx.showToast({
        type: 'none',
        content: '支付金额必须大于0元',
        duration: 600,
      });
      return
    }
    if (!this.data.checkBox) {
      wx.showToast({
        type: 'none',
        content: '请同意服务条款',
        duration: 600,
      });
      return
    }
    const realAmount = format.amountClear(d.payAmountInput)
    console.log(this.data)
    if (!app.globalData.station || !app.globalData.station.alipay_store_id) {
      var store_id = app.globalData.mainStore
    } else {
      var store_id = app.globalData.station.alipay_store_id
    }
    let serviceCharge,periodCost,number
    if (this.data.payType == 7) {
      serviceCharge = this.data.selectHuabei.serviceCharge
      periodCost = this.data.selectHuabei.periodCost
      number = this.data.selectHuabei.number
    }
    
    payModel.recharge(this.data.payType,amount, realAmount.toFixed(0), d.recharge.phone, store_id,serviceCharge,periodCost,number).then(res => {
      console.log(res)
      if (res && res.tradeNo) {
        payModel.myPay('recharge',res.tradeNo, realAmount,'','','',res.orderId)
      } else {
        if (res && res.desc ) {
          wx.showToast({
            type: 'none',
            content: res.desc,
            duration: 600,
          });
        } else {
          wx.showToast({
            type: 'none',
            content: '充值失败',
            duration: 600,
          });
        }
      }
    });
  },
  getCouponListByOrderId() {
    let vm = this
    rechargeModel.getCouponListByOrderId().then(res => {
      if (res.activeName || res.src) {
        vm.setData({
          Registeractive: res,
        });
        vm.setData({
          openPop: true,
        })
        
      }
      console.log(res)
    })
  },
  onCounterPlusOne() {
    this.setData({
      openPop: false,
      // modalOpened4: true,
    })
    // app.globalData.ifSetPaw = 0
  },
  loadUserInfo() {
    app.getUserInfo().then(
      user => {
        this.setData({
          user,
        });
      },
      () => {
        // 获取用户信息失败
      }
    );
  },
  loadMyAccount() {
    // rechargeModel.loadMyAccount().then(res => {
    //   console.log(res)
    //   wx.stationName = '999999'
    //   this.setData({
    //     my: res
    //   })
    // })
  },
  onModalClick21() {
    this.setData({
      modalOpened4: false,
    });
    wx.navigateTo({
      url: '/pages/account/setPaw/setPaw'
    })
  },
  onModalClose21() {
    this.setData({
      modalOpened4: false,
    });
    wx.reLaunch({
      url: '/pages/my/my'
    })
    // wx.navigateBack()
    
  },
  checkOriginPwd() {
    accountmodel.checkOriginPwd().then(res => {
        console.log(res)
        if (res && res.code == '00') {
          this.setData({
            openTicketType: res.openTicketType
          });
          if (res.pinStatus == 0) {
            this.setData({
              // modalOpened4: true,
              openTicketType: res.openTicketType

            });
            app.globalData.ifSetPaw = 0
          } else {
            app.globalData.ifSetPaw = 1
            this.getActiveParam()
          }
        } else {
          wx.showToast({
            type: 'none',
            content: '接口错误',
            duration: 1000,
          });
        }
      })
  },
  // 变更开票类型
  checkout(e) {
    const index = e.currentTarget.dataset.index
    if (index == this.data.openTicketType) {
      return
    } else {
      this.modifyOpenTicketType(index)
    }
  },
  // 变更开票类型
  modifyOpenTicketType(index) {
    invioceModel.modifyOpenTicketType(index).then(res => {
      console.log(res)
      if (res && res.code == '00') {
        this.setData({
          'openTicketType': index
        })
      } else {
        if (res && res.msg) {
          wx.showToast({
            type: 'none',
            content: res.msg,
            duration: 1000,
          });
        } else {
          wx.showToast({
            type: 'none',
            content: '变更开票类型失败',
            duration: 1000,
          });
        }
        
      }
      
    })
  },
  // 获取充值活动
  getActiveParam() {
    let vm = this
    rechargeModel.getActiveParam('actice').then(res => {
      console.log(res)
      if (res) {
        if (res.rechargeParam) {
          this.setData({
            'quickAmount': res.rechargeParam
          })
        }
        if (res.active && res.activeDetail) {
          this.setData({
            'rechargeActive[name]': res.active.bigSlogan,
            'rechargeActive[mallSlogan]': res.active.mallSlogan,
            'rechargeActive[activeDetail]': res.activeDetail
          })
        }
      } else {
        wx.showToast({
          type: 'none',
          content: '获取充值活动失败',
          duration: 1000,
        });
      }
    })
  },
  toPage(e) {
    const page = e.currentTarget.dataset.url
    if (page == '/pages/rechargeActive/rechargeActive') {
      wx.navigateTo({
        url: page + '?activeDetail=' + encodeURIComponent(JSON.stringify(this.data.rechargeActive.activeDetail))
      })
    } else {
      wx.navigateTo({
        url: page
      })
    }
  },
  radioChange(e) {
    let item = e.currentTarget.dataset
    let taxRate = this.data.taxRate
    if (this.data.payAmountInput < 100) {
      wx.showToast({
        type: 'none',
        content: '花呗分期最低充值金额为100元，请修改您的充值金额',
        duration: 1000,
      });
      return
    }
    if (this.data.huabeiSelect) {
      this.setData({
        huabeiSelect: false,
        selectHuabei: '',
        payType: 2,
      })
      return
    }
    let payAmountInput = this.data.payAmountInput
    this.setData({
      huabeiSelect: true,
      payType: 7,
      huabeiIndex: 0,
      'huabei': [{serviceCharge: parseInt(payAmountInput*100*taxRate[0]/3),taxRate: taxRate[0],number: 3,periodCost: parseInt(payAmountInput*100/3) + parseInt(payAmountInput*100*taxRate[0]/3)},
                {serviceCharge: parseInt(payAmountInput*100*taxRate[1]/6),taxRate: taxRate[1],number: 6,periodCost: parseInt(payAmountInput*100/6)+parseInt(payAmountInput*100*taxRate[1]/6)},
                {serviceCharge: parseInt(payAmountInput*100*taxRate[2]/12),taxRate: taxRate[2],number: 12,periodCost: parseInt(payAmountInput*100/12) +parseInt(payAmountInput*100*taxRate[2]/12)}],
      'selectHuabei' : {serviceCharge: parseInt(payAmountInput*100*taxRate[0]/3),taxRate: taxRate[0],number: 3,periodCost: parseInt(payAmountInput*100/3) + parseInt(payAmountInput*100*taxRate[0]/3)}
    })
  },
  //  选择花呗期数
  changehuabei(e) {
    console.log(e)
    let item = e.currentTarget.dataset
    this.setData({
      huabeiIndex: item.index,
      selectHuabei: item.item,
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})